package javase.collections;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetPerformanceTest {

	public static void main(String[] args) {
		HashSet<Integer> hashSet = new HashSet<Integer>();
		TreeSet<Integer> treeSet = new TreeSet<Integer>();
		LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>();
		testPerformance(hashSet);
		testPerformance(treeSet);
		testPerformance(linkedHashSet);
		
		// TODO try to use conversion constructor
	}
	
	private static void fillOutSet(Set<Integer> set, int capacity) {
		for (int i = 0; i < capacity; i++) {
			set.add(new Integer(capacity - i));
		}
	}
	
	private static void iterateSet(Set<Integer> set) {
		Iterator<Integer> iterator = set.iterator();
		while (iterator.hasNext()) {
			iterator.next();
		}
	}
	
	private static void iterateAndClearSet(Set<Integer> set) {
		Iterator<Integer> iterator = set.iterator();
		while (iterator.hasNext()) {
			iterator.next();
			iterator.remove();
		}
	}
	
	private static void testPerformance(Set<Integer> set) {
		System.out.println(set.getClass().getSimpleName());
		int setCapacity = 10000;
		
		Date initializationStart = new Date();
		fillOutSet(set, setCapacity);
		Date initializationFinish = new Date();
		System.out.println("Initialization finished in " + (initializationFinish.getTime() - initializationStart.getTime()) + " ms");
		
		Date iterationStart = new Date();
		iterateSet(set);
		Date iterationFinish = new Date();
		System.out.println("Iteration finished in " + (iterationFinish.getTime() - iterationStart.getTime()) + " ms");
		
//		System.out.println(set);
		Date cleanStart = new Date();
		iterateAndClearSet(set);
		Date cleanFinished = new Date();
		System.out.println("Cleaning finished in " + (cleanFinished.getTime() - cleanStart.getTime()) + " ms");
		System.out.println("====================================");
	}
}
